package com.eureka.client.web.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import com.eureka.client.mobile.user.User;
import com.eureka.client.service.redis.RedisService;
import com.eureka.client.util.SNSUserInfo;
import com.eureka.client.util.WeiXinUtil;
import com.eureka.client.util.WeixinOauth2Token;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/index")
public class loginController {
	@Autowired
	RedisService redisService;
	
	 @Autowired  
	 RestTemplate restTemplate;  
	
	private static String ul = "http://wanghao.tunnel.qydev.com";
    //返回微信二维码，可供扫描登录
    @SuppressWarnings("static-access")
	@RequestMapping(value = "/weixin")
    @ResponseBody
    public Map<String,Object> weixin(HttpServletRequest request) throws IOException {
        Map<String,Object> map = new HashMap<String,Object>();
        WeiXinUtil wxU = new WeiXinUtil();
        //http://www.shike.com.cn/index/WeiXinTest是手机用户扫码后会执行的后台方法
        //www.shike.com.cn此域名要与微信公共平台配置的一致
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=wx4d761945f58ce4d2&" +
                "redirect_uri=http://www.shanhaibian.com/eurekaClient/index/WeiXinTest&" +
                "response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        //将url转换成短链接，提高扫码速度跟成功率
        String shorturl=wxU.shortURL(url, wxU.appid, wxU.appSecret);
        map.put("shorturl", shorturl);
        return map;
    }

    int type = 0;
    String type2 = "";
    //判断用户是否扫码登录成功，以便于前台页面跳转
    @RequestMapping(value = "successDL")
    @ResponseBody
    public Map<String,Object> successDL(String a){
        Map<String,Object> map = new HashMap<String,Object>();
        try
        {
            Thread.sleep(500);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        if("ok".equals(a)){
            type=1;
        }
        if(type==1){
            map.put("userId", type2);
        }
        map.put("type", type);
        return map;
    }



    @RequestMapping(value = "/type")
    @ResponseBody
    public void type(int a){
        type=a;
    }

    //微信获取用户信息
    @RequestMapping(value = "/WeiXinTest")
    public ModelAndView WeiXinTest(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws IOException{
        ModelAndView mav = new ModelAndView();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String code = request.getParameter("code");
        // 通过code获取access_token
        WeixinOauth2Token oauth2Token =WeiXinUtil.getOauth2AccessToken(WeiXinUtil.appid, WeiXinUtil.appSecret, code);
        System.out.println(oauth2Token.toString());
        String accessToken=oauth2Token.getAccessToken();
        String openId=oauth2Token.getOpenId();
        //获取到用户的基本信息
        SNSUserInfo snsUserInfo=null;
        if(type==0){
            snsUserInfo = WeiXinUtil.getSNSUserInfo(accessToken, openId);
        }
        if(snsUserInfo!=null){
        	
        	
        	
        	System.out.println(snsUserInfo.getCountry());
        	
        	System.out.println(snsUserInfo.getProvince());
        	
        	System.out.println(snsUserInfo.getNickname());
        	
        	System.out.println(snsUserInfo.getHeadImgUrl());
        	
            HttpSession session = request.getSession();

            session.setAttribute("snsUserInfo", snsUserInfo);
            //证明获取到了微信用户基本信息
            type=1;
            String id = snsUserInfo.getOpenId();
            type2=id;//可用作用户id，此值是微信用户的唯一识别
//		   查询库中是否有user
            /*逻辑写这*/
            
            System.out.println(id);

            //给手机端返回页面，成功，此处无法给pc端进行页面跳转
            mav.setViewName("info");
        }else{
            //给手机端返回页面，失败，此处无法给pc端进行页面跳转
            mav.setViewName("info1");
        }
        return mav;
    }
    //扫码登录成功后，将用户信息放入session中，并且跳转页面
    @RequestMapping(value = "fangSession")
    public ModelAndView fangSession(HttpServletRequest request,String userId){
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
         /*  User sessionuser=new User();
           sessionuser.setUserId(Long.valueOf(userId));*/
/*----------建议存完整的user，此时session中的user只有Id---------------*/
           session.setAttribute("userId", userId);
           
           SNSUserInfo snsUserInfo = (SNSUserInfo) session.getAttribute("snsUserInfo");
           session.getAttribute("userId");
           session.setAttribute("snsUserInfo", snsUserInfo);
           String userIdas  = (String) session.getAttribute("userId");
           System.out.println(userIdas);
           mav.setViewName("info");  
           return mav;
    }



    //返回微信二维码，可供扫描登录
    @SuppressWarnings("static-access")
	@RequestMapping(value = "/page")
    public ModelAndView weixin1(HttpServletRequest request,HttpSession session) throws IOException {
        ModelAndView mav = new ModelAndView();
      /*  WeiXinUtil wxU = new WeiXinUtil();
        //http://www.shike.com.cn/index/WeiXinTest是手机用户扫码后会执行的后台方法
        //www.shike.com.cn此域名要与微信公共平台配置的一致
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=wx4d761945f58ce4d2&" +
                "redirect_uri=http://www.shanhaibian.com/eurekaClient/index/WeiXinTest&" +
                "response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        //将url转换成短链接，提高扫码速度跟成功率
        String shorturl=wxU.shortURL(url, wxU.appid, wxU.appSecret);
       // session.setAttribute("shorturl", shorturl);
        request.setAttribute("shorturl", shorturl);*/
        mav.setViewName("NewFile");
        return mav;
    }
    @RequestMapping(value = "/sessions", method = RequestMethod.GET)  
    @ResponseBody
    public Object sessions (HttpServletRequest request){  
        Map<String, Object> map = new HashMap<>();  
        map.put("sessionId", request.getSession().getId());  
        map.put("message", request.getSession().getAttribute("map"));  
        map.put("message", request.getSession().getAttribute("username"));  
return map;  
    }  
    @ResponseBody
    @RequestMapping(value = "/first", method = RequestMethod.GET)  
    public Map<String, Object> firstResp (HttpServletRequest request){  
        Map<String, Object> map = new HashMap<>();  
        request.getSession().setAttribute("map", request.getRequestURL());
        request.getSession().setAttribute("username", "15075182791");
        redisService.set("username","15075182791");
        return map;  
    }  
    @SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping(value = "/weixinPay")
    private Map<String, Object>  weixinPay(HttpServletRequest request,String query) throws IOException{
		
    	Map<String, Object> map = new HashMap<>();  	
    	
		String url = ul+"/WxDemo/weixinPay"; 
 
		
		map = restTemplate.getForEntity(url, Map.class).getBody();  
		 
		
		// map = restTemplate.postForEntity(url,RequestMethod.POST,Map.class).getBody();
     return map;  
	 
	 
	 
}
}
